"""
人脸检测模块
负责从图像中检测人脸位置
"""

import face_recognition
from typing import List, Tuple


def detect_faces(image_path: str) -> List[Tuple[int, int, int, int]]:
    """
    检测图像中的人脸位置
    :param image_path: 图像路径
    :return: 人脸边界框列表 [(top, right, bottom, left)]
    """
    try:
        # 加载图像
        image = face_recognition.load_image_file(image_path)
        # 检测人脸位置，使用更准确的模型
        # model参数可以是'hog'（较快）或'cnn'（更准确但需要GPU支持）
        # 在CPU上，我们使用'hog'模型，并设置upsample为1以提高小人脸的检测率
        face_locations = face_recognition.face_locations(image, model="hog", number_of_times_to_upsample=1)
        return face_locations
    except Exception as e:
        print(f"人脸检测失败: {e}")
        return []


def detect_faces_in_video(video_source=0) -> None:
    """
    实时检测视频流中的人脸
    :param video_source: 视频源，默认为摄像头
    """
    try:
        import cv2
    except ImportError:
        print("OpenCV库未安装，请确保已安装opencv-python库")
        return
    
    # 初始化摄像头
    video_capture = getattr(cv2, 'VideoCapture')(video_source)
    
    # 设置摄像头参数以提高图像质量
    video_capture.set(getattr(cv2, 'CAP_PROP_FRAME_WIDTH'), 1280)
    video_capture.set(getattr(cv2, 'CAP_PROP_FRAME_HEIGHT'), 720)
    video_capture.set(getattr(cv2, 'CAP_PROP_FPS'), 30)
    
    while True:
        # 获取一帧视频
        ret, frame = video_capture.read()
        
        # 转换BGR图片到RGB图片 (face_recognition使用RGB)
        rgb_frame = getattr(cv2, 'cvtColor')(frame, getattr(cv2, 'COLOR_BGR2RGB'))
        
        # 查找当前帧中所有人脸的位置
        # 使用更准确的参数
        face_locations = face_recognition.face_locations(rgb_frame, model="hog", number_of_times_to_upsample=1)
        
        # 显示结果
        for (top, right, bottom, left) in face_locations:
            # 在人脸周围画框
            getattr(cv2, 'rectangle')(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        
        # 显示结果图像
        getattr(cv2, 'imshow')('Video', frame)
        
        # 按q退出
        if getattr(cv2, 'waitKey')(1) & 0xFF == ord('q'):
            break
    
    # 释放摄像头
    video_capture.release()
    getattr(cv2, 'destroyAllWindows')()